package chapter05_string;

import sun.reflect.generics.tree.VoidDescriptor;

import javax.print.attribute.Size2DSyntax;
import java.util.HashMap;

/**
 * 描述：是否为变形词
 * @author hl
 * @date 2021/8/7 9:55
 */
public class IsDeformation {
    public static void main(String[] args) {
        String s1 = "123";
        String s2 = "234";
        IsDeformation main = new IsDeformation();
        boolean flag = main.isDeformation2(s1, s2);
        System.out.println(flag);
    }

    /**
     * 如果字符编码值在0~255之间，那么可以申请一个长度为256的数组保存字符串中字符出现的频率
     * @param t
     * @return
     */
    public boolean isDeformation1(String s, String t){
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }
        int[] map = new int[256];
        for (int i = 0; i < s.length(); i++) {
            map[s.charAt(i)]++;
        }
        for (int i = 0; i < t.length(); i++) {
            if (map[t.charAt(i)]-- == 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 如果字符类型很多，那么可以使用哈希表进行存储
     * @param s
     * @param t
     * @return
     */
    public boolean isDeformation2(String s, String t){
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }
        HashMap<Character, Integer> map = new HashMap<>();
        char key;
        for (int i = 0; i < s.length(); i++) {
            key = s.charAt(i);
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            key = t.charAt(i);
            if (!map.containsKey(key) || map.get(key).equals(0)) {
                return false;
            }
            map.put(key, map.get(key) - 1);
        }
        return true;
    }
}
